<template>
	<view class="k-line-box">
		<view class="time_box flex">
			<view class="time_item flex_center" :class="activeTime.id == item.id?'active_time':''"
				v-for="(item,index) in timeList" @tap="handleChoseTime(item)">
				{{item.txt}}
			</view>
		</view>
		<!-- k线图 -->
		<view class="k_line" id="k_line_box" :prop="data" :change:prop="kline.dataChange" :time="activeTime"
			:change:time="kline.timeChange" :lang="lang" :main="activeMainType" :change:main="kline.mainChange"
			:type="activeType" :change:type="kline.typeChange"></view>
		<view class="flex_between">
			<view class="k_line_box">
				<view class="k_line_btn" :class="activeMainType == item ? 'k_line_active' : ''"
					v-for="item in mainIndicators" @click="setMainIndicator(item)">
					{{ item }}
				</view>
			</view>
			<view class="k_line_box">
				<view class="k_line_btn" :class="activeType == item ? 'k_line_active' : ''"
					v-for="item in subIndicators" @click="setSubIndicator(item)">
					{{ item }}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props: ["id"],
		data() {
			return {
				timeList: [{
						type: "HH:mm",
						id: 1,
						txt: "分时",
						value: "1"
					}, {
						type: "HH:mm",
						id: 2,
						txt: "5min",
						value: "5"
					}, //min
					{
						type: "HH:mm",
						id: 3,
						txt: "30min",
						value: "30"
					}, //min
					{
						type: "MM-DD HH:mm",
						id: 4,
						txt: "1h",
						value: "60"
					}, //min
					{
						type: "YYYY-MM-DD",
						id: 5,
						txt: "1d",
						value: "1440"
					}, //day
					{
						type: "YYYY-MM-DD",
						id: 6,
						txt: "1w",
						value: "10080"
					}, //week
					{
						type: "YYYY-MM",
						id: 7,
						txt: "1m",
						value: "43200"
					}, //month

				],
				activeTime: {
					type: "HH:mm",
					id: 1,
					txt: "分时",
					value: "1"
				},
				mainIndicators: ["MA", "BOLL"], // "EMA", "SAR"
				subIndicators: ["VOL", "MA", "MACD", "KDJ"], //"VOL",
				activeMainType: "MA",
				activeType: "VOL",
				lang: uni.getStorageSync("lang"),
				data: [],
				baseUrl: ""
			};
		},
		mounted: async function() {
			this.activeTime = this.timeList[0];
			await this.getChartData();

			this.changeType();
		},
		methods: {
			changeType() {
				if (this.activeTime.id == 1) {
					this.activeTime.txt =
						this.lang == "zh-Hans" ? "分时" : this.lang == "zh-Hant" ? "分時" : "Line";
				}
			},
			async getChartData() {
				this.baseUrl = uni.getStorageSync("baseUrl")
				uni.showLoading({
					title: "加载中~"
				})
				await uni.request({
					url: this.baseUrl + "/api/product/kline",
					method: "POST",
					data: {
						token: uni.getStorageSync("token"),
						time: this.activeTime.value,
						pro_id: this.id
					},
					dataType: "json"
				}).then(res => {
					uni.hideLoading()
					if (res[0]) {
						return
					} else {
						let data = res[1].data.data
						data.forEach((item) => {
							this.data.push({
								close: item.close * 1,
								high: item.high * 1,
								low: item.low * 1,
								open: item.open * 1,
								timestamp: item.issuetime * 1000,
								volume: item.volume * 1,
							})
						})
						this.data = this.data.reverse()
						// console.log(this.data, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
					}
				})
				// this.loading = false;
			},
			async handleChoseTime(time, key) {
				if (this.activeTime.id == time.id) {
					return;
				}
				this.activeTime = this.timeList.filter((item) => {
					return item.id == time.id;
				});
				this.activeTime = this.activeTime[0];
				await this.getChartData();
				this.changeType();
			},
			setMainIndicator(name) {
				this.activeMainType = name;
			},
			setSubIndicator(name) {
				this.activeType = name;
			},
		},
	};
</script>
<script module="kline" lang="renderjs">
	import klinecharts from 'klinecharts'
	import config from "./config";

	function getTooltipOptions(candleShowType, candleShowRule, indicatorShowRule) {
		return {
			candle: {
				tooltip: {
					showType: candleShowType,
					showRule: candleShowRule,
					custom: (data) => {
						const {
							prev,
							current
						} = data;
						const prevClose = prev ? prev.close : current.open;
						const change = ((current.close - prevClose) / prevClose) * 100;
					},
				},
			},
			indicator: {
				tooltip: {
					showRule: indicatorShowRule,
				},
			},
		};
	}
	klinecharts.registerLocale("zh-Hant", {
		time: "時間：",
		open: "開：",
		high: "高：",
		low: "低：",
		close: "收：",
		volume: "成交量：",
	});
	export default {
		data() {
			return {
				chart: null,
				opt: {
					customApi: {
						formatDate: (dateTimeFormat, timestamp, format, type) =>
							klinecharts.utils.formatDate(dateTimeFormat, timestamp, this.activeTime.type),
					},
				},
				paneId: "VOL"
			}
		},
		mounted: async function() {
			// console.log(config)
			this.chart = klinecharts.init("k_line_box", {
				...config,
				...this.opt
			});
			this.paneId = this.chart.createIndicator("VOL");
			if (this.lang == "zh-Hans") {
				this.chart.setLocale("zh-Hans");
			} else if (this.lang == "zh-Hant") {
				this.chart.setLocale("zh-Hant");
			} else {
				this.chart.setLocale("en");
			}
			this.chart.createIndicator(this.activeMainType, false, {
				id: "candle_pane"
			});
			this.chart.createIndicator(this.activeType, false, {
				id: this.paneId
			});
			this.chart.setPriceVolumePrecision(3, 3);
			this.chart.setStyles(getTooltipOptions("rect", "follow_cross", "follow_cross"));
		},
		methods: {
			timeChange(newValue, oldValue, ownerInstance, instance) {
				// console.log('service层中的time发生变化', newValue)
				if (!oldValue) {
					return
				}
				if (newValue.id == 1) {
					this.chart.setStyles({
						candle: {
							type: "area",
						},
					});
					this.chart.setStyles(getTooltipOptions("rect", "follow_cross", "follow_cross"));
				} else {
					this.chart.setStyles({
						candle: {
							type: "candle_solid",
						},
					});
					this.chart.setStyles(getTooltipOptions("rect", "follow_cross", "follow_cross"));
				}

			},
			dataChange(newValue, oldValue, ownerInstance, instance) {
				// console.log('service层中的data发生变化', newValue)
				if (!oldValue) {
					return
				}
				this.chart.applyNewData(newValue);
			},
			mainChange(newValue, oldValue, ownerInstance, instance) {
				// console.log('service层中的main发生变化', newValue)
				if (!oldValue) {
					return
				}
				this.chart.createIndicator(newValue, false, {
					id: "candle_pane"
				});
			},
			typeChange(newValue, oldValue, ownerInstance, instance) {
				// console.log('service层中的main发生变化', newValue)
				if (!oldValue) {
					return
				}
				this.chart.createIndicator(newValue, false, {
					id: this.paneId
				});
			},
			unmounted() {
				klinecharts.dispose("k_line_box");
			}
		}
	}
</script>
<style lang="less" scoped>
	.k-line-box {
		width: 100%;
		background: transparent;
		position: relative;
		display: flex;
		flex-direction: column;
		padding: 0 24rpx;

		.time_box {
			height: 112rpx;

			.time_item {
				flex: 1;
				font-size: 28rpx;
				font-weight: 400;
				color: hsla(0, 0%, 100%, .68);
				position: relative;
				height: 100%;

				&::after {
					content: "";
					position: absolute;
					left: 50%;
					bottom: 0;
					width: 46rpx;
					height: 8rpx;
					background: transparent;
					border-radius: 4rpx;
					transform: translateX(-50%);
				}
			}

			.active_time {
				color: #9984dc;

				&::after {
					background: #9984dc;
				}
			}
		}

		.k_line_box {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			background: transparent;
			font-size: 28rpx;
			font-weight: 400;
			color: hsla(0, 0%, 100%, .68);

			.k_line_btn {
				margin: 10rpx;

			}

			.k_line_active {
				color: #9984dc;
			}
		}

		.k_line {
			height: 650rpx;
		}
	}
</style>